package com.example.rabbitmqtest;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.boot.autoconfigure.amqp.RabbitProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author :  wudgaby
 * @Version :  since 1.0
 * @Date :  2021/5/8 15:32
 * @Desc :
 */
@Configuration
public class RabbitMQConfig {

    public static final String topicExchangeName = "topic-exchange";
    public static final String fanoutExchange = "fanout-exchange";
    public static final String headersExchange = "headers-exchange";

    public static final String queueName = "hyyjQueue";

    //声明队列
    @Bean
    public Queue queue() {
        //Queue(String name, boolean durable, boolean exclusive, boolean autoDelete)
        return new Queue(queueName, true, false, false);
    }

    //声明Topic交换机
    @Bean
    TopicExchange topicExchange() {
        return new TopicExchange(topicExchangeName);
    }

    //将队列与Topic交换机进行绑定，并指定路由键
    @Bean
    Binding topicBinding(Queue queue, TopicExchange topicExchange) {
        return BindingBuilder.bind(queue).to(topicExchange).with("org.cord.#");
    }

    //声明fanout交换机
    @Bean
    FanoutExchange fanoutExchange() {
        return new FanoutExchange(fanoutExchange);
    }

    //将队列与fanout交换机进行绑定
    @Bean
    Binding fanoutBinding(Queue queue, FanoutExchange fanoutExchange) {
        return BindingBuilder.bind(queue).to(fanoutExchange);
    }

    //声明Headers交换机
    @Bean
    HeadersExchange headersExchange() {
        return new HeadersExchange(headersExchange);
    }

    //将队列与headers交换机进行绑定
    @Bean
    Binding headersBinding(Queue queue, HeadersExchange headersExchange) {
        Map<String, Object> map = new HashMap<>();
        map.put("First","A");
        map.put("Fourth","D");
        //whereAny表示部分匹配，whereAll表示全部匹配
//        return BindingBuilder.bind(queue).to(headersExchange).whereAll(map).match();
        return BindingBuilder.bind(queue).to(headersExchange).whereAny(map).match();
    }

    /**
     * 配置MQ连接信息
     *
     * @return
     */
    /*@Bean
    public ConnectionFactory connectionFactory(RabbitProperties rabbitProperties) {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        String virtualHost = "/".equals(rabbitProperties.getVirtualHost()) ? rabbitProperties.getVirtualHost() : "/" + rabbitProperties.getVirtualHost();
        String url = "amqp://" + rabbitProperties.getUsername() + ":" + rabbitProperties.getPassword() + "@" + rabbitProperties.getHost() + ":" + rabbitProperties.getPort();
        connectionFactory.setUri(url);
        return connectionFactory;
    }*/
}